//
//  HomeViewController.m
//  A段项目,漫画
//
//  Created by dllo on 15/4/20.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "HomeViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface HomeViewController ()
@property(nonatomic, retain)NSMutableArray *myBanners;
@property(nonatomic, retain)UITableView *cartoonTable;
@property(nonatomic, retain)NSNumber *bannerCount;
@property(nonatomic, assign)NSInteger allCount;
@property(nonatomic, retain)NSMutableArray *ComicListArr;
@property(nonatomic, retain)limitFree *myLimitFree;
@property(nonatomic, retain)manga *myManga;
@property(nonatomic, retain)ad *myAd;
@property(nonatomic, retain)NSMutableArray *myGesArr;
@property(nonatomic, retain)NSString *mySelectedComicID;
@property(nonatomic, copy)void (^myMoreBlock)(NSString *comic_list_id);
@property(nonatomic, retain)UIActivityIndicatorView *myActivity;
//清除缓存
@property(nonatomic, retain)UIAlertView *wipeAlert;
@property(nonatomic, retain)UIView *wipeView;
@property(nonatomic, retain)UIButton *startWipe;
@property(nonatomic, retain)UIProgressView *wipeProgress;
@property(nonatomic, retain)UILabel *currentLabel;
@property(nonatomic, retain)UIButton *cancelWipe;
@property(nonatomic, assign)NSInteger fileCount;
@property(nonatomic, retain)UIAlertView *finishAlert;
//动画
@property(nonatomic, retain)UIView *witeView;
@property(nonatomic, retain)NSMutableArray *witeImageArr;
@property(nonatomic, retain)UIImageView *witeImageView;
@property(nonatomic, retain)UIProgressView *myProgress;
@property(nonatomic, retain)UILabel *myLabel;
@end

@implementation HomeViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.ComicListArr = [NSMutableArray array];
        self.myManga = [[manga alloc] init];
        self.myBanners = [NSMutableArray array];
        self.myManga.mangaData = [NSMutableArray array];
        self.myLimitFree = [[limitFree alloc] init];
        self.myAd = [[ad alloc] init];
        self.myGesArr = [NSMutableArray array];
        
        
    }
    return self;
}
- (void)createWiteImage{
    self.witeImageArr = [NSMutableArray array];
    NSArray *names = @[@"5QEIITX68@[%)D5BN5RH8JD－1（被拖移）.tiff", @"5QEIITX68@[%)D5BN5RH8JD－2（被拖移）.tiff", @"5QEIITX68@[%)D5BN5RH8JD－3（被拖移）.tiff", @"5QEIITX68@[%)D5BN5RH8JD－4（被拖移）.tiff"];
    for (NSString *name in names) {
        UIImage *image = [UIImage imageNamed:name];
        [self.witeImageArr addObject:image];
    }
    self.witeImageView.animationImages = self.witeImageArr;
    //设置播放时间
    self.witeImageView.animationDuration = 0.3;
}
- (void)createAvtivity{
    self.witeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.witeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.witeView];
    [self.witeView release];
    
    //150    150
    self.witeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, WIDTH / 3)];
    self.witeImageView.center = CGPointMake(WIDTH / 2, HEIGHT / 3);
    [self.witeView addSubview:self.witeImageView];
    [self.witeImageView release];
    
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, 30)];
    self.myLabel.center = CGPointMake(WIDTH / 2, HEIGHT / 3 + WIDTH / 6 + 10);
    self.myLabel.text = @"loading..........";
    [self.witeView addSubview:self.myLabel];
    self.myLabel.textAlignment = NSTextAlignmentCenter;

    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView isEqual:self.wipeAlert]) {
        if (buttonIndex == 1) {
            //显示
            [UIView animateWithDuration:1 animations:^{
                [self.view bringSubviewToFront:self.wipeView];
                self.wipeView.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
                self.cartoonTable.userInteractionEnabled = NO;
            } completion:^(BOOL finished) {
                NSArray *sandBoxCache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                NSString *sandBoxCachePath = [sandBoxCache lastObject];
                NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:sandBoxCachePath];
                self.fileCount = files.count;
                self.currentLabel.text = [NSString stringWithFormat:@"缓存文件数量: %ld",self.fileCount];
            }];
        }
    }else if ([alertView isEqual:self.finishAlert]){
        NSLog(@"完成点击");
        [UIView animateWithDuration:1 animations:^{
            self.wipeView.frame = CGRectMake(WIDTH, 0, 300, 150);
            self.cartoonTable.userInteractionEnabled = YES;
            [self.view bringSubviewToFront:self.cartoonTable];
        } completion:^(BOOL finished) {
        }];
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createView];
    [self createAvtivity];
    [self createWiteImage];
    [self dataLoad];
    NSLog(@"播放动画");
    [self.view bringSubviewToFront:self.wipeView];
    [self.witeImageView startAnimating];
}


- (void)createView{
    self.cartoonTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 105)];
    [self.view addSubview:self.cartoonTable];
    [self.cartoonTable release];
    self.cartoonTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.navigationItem.title = @"呵呵动漫";
    self.cartoonTable.delegate = self;
    self.cartoonTable.dataSource = self;
    self.navigationController.navigationBar.translucent = NO;
    
    self.tabBarController.tabBar.translucent = NO;
    //more按钮点击跳转block
    self.myMoreBlock = ^(NSString *comic_list_id){
        MoreCartoonViewController *moreVC = [[MoreCartoonViewController alloc] init];
        moreVC.comic_list_id = comic_list_id;
        [self.navigationController pushViewController:moreVC animated:YES];
    };
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        //轮播
        CGFloat bili = 320 / 720.0;
        return WIDTH * bili;
    }else if(indexPath.row >0 && indexPath.row <= self.ComicListArr.count){
        //连载
        CGFloat bili = 200.0 / 336;
        return WIDTH / 2.2 * bili + 80;
    }else if(indexPath.row == self.ComicListArr.count + 1){
        //限免
        CGFloat bili = 280.0 / 210;
        return WIDTH / 3.5 * bili + 30;
    }else if(indexPath.row == self.ComicListArr.count + 2){
        //日漫
        CGFloat bili = 166.0 / 150;
        return WIDTH / 3.5 * bili + 80;
    }else{
        //猜你喜欢
        CGFloat bili = 200.0 / 336;
        return WIDTH / 2.2 * bili + 80;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        //轮播点击
    }else if(indexPath.row >0 && indexPath.row <= self.ComicListArr.count){
        //连载
    }else if(indexPath.row == self.ComicListArr.count + 1){
        //限免
        self.mySelectedComicID = self.myLimitFree.comic_id;
        CartoonDViewController *cartoonDVC = [[CartoonDViewController alloc] init];
        cartoonDVC.comic_id = self.mySelectedComicID;
        [self.navigationController pushViewController:cartoonDVC animated:YES];
    }else if(indexPath.row == self.ComicListArr.count + 2){
        //日漫
    }else if(indexPath.row == self.ComicListArr.count + 3){
        //猜你喜欢
    }
}

- (void)getSelectedBannerIndex:(NSString *)myID{
    self.mySelectedComicID = myID;
    CartoonDViewController *cartoonDVC = [[CartoonDViewController alloc] init];
    cartoonDVC.comic_id = self.mySelectedComicID;
    [self.navigationController pushViewController:cartoonDVC animated:YES];
}

- (void)getComicListID:(NSString *)myID{
    self.mySelectedComicID = myID;
    CartoonDViewController *cartoonDVC = [[CartoonDViewController alloc] init];
    cartoonDVC.comic_id = self.mySelectedComicID;
    [self.navigationController pushViewController:cartoonDVC animated:YES];
}

- (void)getMangaComicID:(NSString *)myID{
    self.mySelectedComicID = myID;
    CartoonDViewController *cartoonDVC = [[CartoonDViewController alloc] init];
    cartoonDVC.comic_id = self.mySelectedComicID;
    [self.navigationController pushViewController:cartoonDVC animated:YES];
}

- (void)getGuessYouLikeID:(NSString *)myID{
    self.mySelectedComicID = myID;
    CartoonDViewController *cartoonDVC = [[CartoonDViewController alloc] init];
    cartoonDVC.comic_id = self.mySelectedComicID;
    [self.navigationController pushViewController:cartoonDVC animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.ComicListArr.count == 0) {
        return 0;
    }else{
        return self.ComicListArr.count + 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        //轮播
        static NSString *reuse = @"reuse";
        BannerCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[[BannerCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse] autorelease];
        }
        cell.delegate = self;
        cell.myBanners = self.myBanners;
        cell.bannerCount = self.bannerCount;
        [cell.bannerCollection reloadData];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        if (indexPath.row >0 && indexPath.row <= self.ComicListArr.count) {
            //强档推荐
            static NSString *reuse1 = @"reuse1";
            ComicListCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse1];
            if (cell == nil) {
                cell = [[[ComicListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse1] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate = self;
            }
            ComicList *c = self.ComicListArr[indexPath.row - 1];
            cell.myMoreBlock = self.myMoreBlock;
            cell.myData = c.myData;
            cell.comic_list_id = [c.comic_list_id stringValue];
            cell.comicListCount = [c.count integerValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.comicListTitle.text = [NSString stringWithFormat:@"   %@",c.title];
            [cell.comicListCollection reloadData];
            
            NSLog(@"结束动画");
            [self.witeImageView stopAnimating];
            [self.view bringSubviewToFront:self.cartoonTable];
            
            
            return cell;
        }else if (indexPath.row == self.ComicListArr.count + 1) {
            //今日限免
            static NSString *reuse2 = @"reuse2";
            limitFreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse2];
            if (cell == nil) {
                cell = [[[limitFreeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse2] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.mainTitle.text = self.myLimitFree.mainTitle;
            NSURL *url = [NSURL URLWithString:self.myLimitFree.cover_url];
            UIImage *placeImage = [UIImage imageNamed:@"FOR@{XC4(JCI7}{P@Y]({{1－1（被拖移）.tiff"];
            [cell.limitImage sd_setImageWithURL:url placeholderImage:placeImage];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.limitTitle.text = [NSString stringWithFormat:@" %@",self.myLimitFree.title];
            cell.artistName.text = [NSString stringWithFormat:@"作者: %@",self.myLimitFree.artist_name];
            cell.grade_ave.text = [NSString stringWithFormat:@"评分: %@",self.myLimitFree.grade_ave];
            cell.brief_intrd.text = [NSString stringWithFormat:@"简介: %@",self.myLimitFree.brief_intrd];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if(indexPath.row == self.ComicListArr.count + 2){
            //日漫专区
            static NSString *reuse3 = @"reuse3";
            MangaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse3];
            if (cell == nil) {
                cell = [[[MangaTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse3] autorelease];
                cell.delegate = self;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.comic_list_id = [self.myManga.comic_list_id stringValue];
            cell.myMoreBlock = self.myMoreBlock;
            [cell.mangaCollection reloadData];
            cell.mangaTitle.text = [NSString stringWithFormat:@"   %@",self.myManga.title];
            cell.mangaData = self.myManga.mangaData;
            return cell;
        }else if(indexPath.row == self.ComicListArr.count + 3){
            //猜你喜欢
            static NSString *reuse4 = @"reuse4";
            GuessYouLikeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse4];
            if (cell == nil) {
                cell = [[[GuessYouLikeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse4] autorelease];
                cell.delegate = self;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.GuessCollection reloadData];
            cell.GuessTitle.text = @"   猜你喜欢";
            cell.GuessData = self.myGesArr;
            return cell;
        }else{
            UITableViewCell *cellNULL = [[UITableViewCell alloc] init];
            return cellNULL;
        }
    }
}

- (void)dataLoad{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://mobilev3.ac.qq.com/Home/homePageDetailForIos/local_version/2.3.2/channel/1001/guest_id/921199FA-97DD-457B-80FA-5A7E1D0FC7BA/uin/null" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = (NSDictionary*)responseObject;
        NSDictionary *dataDic = dic[@"data"];
        self.allCount = dataDic.count;
        //ad解析
        NSMutableDictionary *adDic = dataDic[@"ad"];
        [self.myAd setValuesForKeysWithDictionary:adDic];
        //guessYouLike解析
        NSMutableDictionary *gesDic = dataDic[@"guessYouLike"];
        NSMutableArray *gesDataArr = gesDic[@"data"];
        for (NSMutableDictionary *gesDataDic in gesDataArr) {
            ComicListData *cd = [[ComicListData alloc] init];
            [cd setValuesForKeysWithDictionary:gesDataDic];
            [self.myGesArr addObject:cd];
            [cd release];
        }
        NSLog(@"%ld",self.myGesArr.count);
        //limitFree解析
        NSMutableDictionary *limitFreeDic = dataDic[@"limitFree"];
        self.myLimitFree.mainTitle = limitFreeDic[@"title"];
        NSMutableDictionary *dataLimit = limitFreeDic[@"data"];
        [self.myLimitFree setValuesForKeysWithDictionary:dataLimit];
        //manga解析
        NSMutableDictionary *mangaDic = dataDic[@"manga"];
        [self.myManga setValuesForKeysWithDictionary:mangaDic];
        NSMutableArray *dataManga = mangaDic[@"data"];
        for (NSMutableDictionary *dic in dataManga) {
            mangaData *md = [[mangaData alloc] init];
            [md setValuesForKeysWithDictionary:dic];
            [self.myManga.mangaData addObject:md];
            [md release];
        }
        //comiclist解析
        for (NSInteger i = 1; i < 10; i++) {
            NSString *str = [NSString stringWithFormat:@"comicList%ld",i];
            ComicList *comiclist = [[ComicList alloc] init];
            [comiclist setValuesForKeysWithDictionary:[dataDic objectForKey:str]];
            NSMutableDictionary *comicListDic = [dataDic objectForKey:str];
            NSMutableArray *dataArr = [comicListDic objectForKey:@"data"];
            for (NSMutableDictionary *tempDic in dataArr) {
                ComicListData *comicData = [[ComicListData alloc] init];
                [comicData setValuesForKeysWithDictionary:tempDic];
                [comiclist.myData addObject:comicData];
            }
            [self.ComicListArr addObject:comiclist];
            [comiclist release];
        }
        //banner解析
        NSDictionary *bannerDic = dataDic[@"banner"];
        self.bannerCount = bannerDic[@"count"];
        NSArray *dataArr = bannerDic[@"data"];
        for (NSMutableDictionary *tempDic in dataArr) {
            banner *b = [[banner alloc] init];
            [b setValuesForKeysWithDictionary:tempDic];
            [self.myBanners addObject:b];
            [b release];
        }
        NSLog(@"数据请求成功");
        [self.cartoonTable reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"数据请求失败");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
